<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import Chart from 'chart.js/auto';

const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
  title: {
    type: String,
    required: true,
  },
  chartType: {
    type: String,
    default: 'bar',
  },
});

const chartRef = ref(null);
let chartInstance = null; // 用于存储 Chart 实例

onMounted(() => {
  const ctx = chartRef.value.getContext('2d');
  if (ctx) {
    // 清除之前的图表实例（如果存在）
    if (chartInstance) {
      chartInstance.destroy();
    }
    chartInstance = new Chart(ctx, {
      type: props.chartType,
      data: {
        labels: props.data.labels,
        datasets: [{
          label: props.title,
          data: props.data.values,
          backgroundColor: [
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)'
          ],
          borderColor: [
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)'
          ],
          borderWidth: 1,
        }],
      },
      options: {
        responsive: true,
        plugins: {
          legend: {
            position: 'top',
          },
          tooltip: {
            mode: 'index',
            intersect: false,
            callbacks: {
              label: (tooltipItem) => {
                return `值: ${tooltipItem.raw}`;
              },
            },
          },
        },
        scales: {
          y: {
            beginAtZero: true,
          },
        },
        onClick: (event) => {
          const activePoints = chartInstance.getElementsAtEventForMode(event, 'nearest', {intersect: true}, false);
          if (activePoints.length) {
            const {index} = activePoints[0];
            const value = props.data.values[index];
            console.log(`详细信息: ${value}`); // 使用 console.log 替代 alert
          }
        },
        animation: {
          duration: 1000,
        },
      },
    });
  }
});

// 在组件卸载时销毁 Chart 实例
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.destroy();
    chartInstance = null;
  }
});
</script>

<template>
  <div class="chart-container">
    <h2>{{ title }}</h2>
    <canvas ref="chartRef"></canvas>
  </div>
</template>

<style scoped>
.chart-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: transform 0.2s ease-in-out;
}

.chart-container:hover {
  transform: translateY(-5px);
}

.chart-container h2 {
  font-size: 1.2em;
  margin-bottom: 10px;
  color: #333;
}

canvas {
  width: 100%;
  height: auto;
}
</style>



